/**
 * Custom Confirm 组件
 * 一个功能强大、高度可定制的确认对话框组件
 * 
 * @author 前端工程师-阿强
 * @version 1.0.0
 */

class CustomConfirm {
    constructor() {
        this.instances = [];
        this.zIndex = 2000;
        this.defaults = {
            title: '提示',
            message: '',
            type: 'info', // info, success, warning, error
            showCancelButton: true,
            showConfirmButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: '',
            cancelButtonClass: '',
            center: false,
            roundButton: false,
            closeOnClickModal: true,
            closeOnPressEscape: true,
            showClose: true,
            beforeClose: null,
            callback: null,
            customClass: '',
            width: 'auto',
            top: '15vh'
        };
        
        this.init();
    }

    init() {
        // 绑定全局ESC键事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.handleEscapeKey();
            }
        });
    }

    /**
     * 显示确认对话框
     * @param {string|object} options - 配置选项或消息文本
     * @returns {Promise} - 返回Promise对象
     */
    show(options = {}) {
        // 如果传入的是字符串，则作为message处理
        if (typeof options === 'string') {
            options = { message: options };
        }

        const config = Object.assign({}, this.defaults, options);
        
        return new Promise((resolve, reject) => {
            const instance = this.createInstance(config, resolve, reject);
            this.instances.push(instance);
            this.renderInstance(instance);
        });
    }

    /**
     * 创建实例
     */
    createInstance(config, resolve, reject) {
        const id = 'custom-confirm-' + Date.now() + Math.random().toString(36).substr(2, 9);
        
        return {
            id,
            config,
            resolve,
            reject,
            element: null,
            zIndex: this.zIndex++
        };
    }

    /**
     * 渲染实例
     */
    renderInstance(instance) {
        const { config } = instance;
        
        // 创建容器
        const container = document.createElement('div');
        container.className = 'custom-confirm-container';
        container.id = instance.id;
        container.style.zIndex = instance.zIndex;
        
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'custom-confirm-overlay';
        
        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = `custom-confirm ${config.type}`;
        
        if (config.center) {
            dialog.classList.add('center');
        }
        
        if (config.customClass) {
            dialog.classList.add(config.customClass);
        }
        
        if (config.width !== 'auto') {
            dialog.style.width = config.width;
        }
        
        // 创建头部
        const header = this.createHeader(config, instance);
        
        // 创建主体
        const body = this.createBody(config);
        
        // 创建底部
        const footer = this.createFooter(config, instance);
        
        // 组装对话框
        if (header) dialog.appendChild(header);
        dialog.appendChild(body);
        if (footer) dialog.appendChild(footer);
        
        overlay.appendChild(dialog);
        container.appendChild(overlay);
        
        // 绑定事件
        this.bindEvents(container, overlay, instance);
        
        // 添加到页面
        document.body.appendChild(container);
        instance.element = container;
        
        // 显示动画
        requestAnimationFrame(() => {
            overlay.classList.add('show');
        });
    }

    /**
     * 创建头部
     */
    createHeader(config, instance) {
        if (!config.title && !config.showClose) {
            return null;
        }
        
        const header = document.createElement('div');
        header.className = 'custom-confirm-header';
        
        if (config.title) {
            const title = document.createElement('h4');
            title.className = 'custom-confirm-title';
            title.textContent = config.title;
            header.appendChild(title);
        }
        
        if (config.showClose) {
            const closeBtn = document.createElement('button');
            closeBtn.className = 'custom-confirm-close';
            closeBtn.innerHTML = '×';
            closeBtn.onclick = () => this.handleAction('close', instance);
            header.appendChild(closeBtn);
        }
        
        return header;
    }

    /**
     * 创建主体
     */
    createBody(config) {
        const body = document.createElement('div');
        body.className = 'custom-confirm-body';
        
        const content = document.createElement('div');
        content.className = 'custom-confirm-content';
        
        // 创建图标
        const icon = document.createElement('div');
        icon.className = 'custom-confirm-icon';
        
        const iconMap = {
            info: 'i',
            success: '✓',
            warning: '!',
            error: '×'
        };
        
        icon.textContent = iconMap[config.type] || iconMap.info;
        content.appendChild(icon);
        
        // 创建消息
        const message = document.createElement('div');
        message.className = 'custom-confirm-message';
        
        if (typeof config.message === 'string') {
            message.textContent = config.message;
        } else {
            message.appendChild(config.message);
        }
        
        content.appendChild(message);
        body.appendChild(content);
        
        return body;
    }

    /**
     * 创建底部
     */
    createFooter(config, instance) {
        if (!config.showCancelButton && !config.showConfirmButton) {
            return null;
        }
        
        const footer = document.createElement('div');
        footer.className = 'custom-confirm-footer';
        
        if (config.showCancelButton) {
            const cancelBtn = document.createElement('button');
            cancelBtn.className = `custom-confirm-btn cancel ${config.cancelButtonClass}`;
            
            if (config.roundButton) {
                cancelBtn.classList.add('round');
            }
            
            cancelBtn.textContent = config.cancelButtonText;
            cancelBtn.onclick = () => this.handleAction('cancel', instance);
            footer.appendChild(cancelBtn);
        }
        
        if (config.showConfirmButton) {
            const confirmBtn = document.createElement('button');
            confirmBtn.className = `custom-confirm-btn confirm ${config.type} ${config.confirmButtonClass}`;
            
            if (config.roundButton) {
                confirmBtn.classList.add('round');
            }
            
            confirmBtn.textContent = config.confirmButtonText;
            confirmBtn.onclick = () => this.handleAction('confirm', instance);
            footer.appendChild(confirmBtn);
        }
        
        return footer;
    }

    /**
     * 绑定事件
     */
    bindEvents(container, overlay, instance) {
        const { config } = instance;
        
        // 点击遮罩关闭
        if (config.closeOnClickModal) {
            overlay.onclick = (e) => {
                if (e.target === overlay) {
                    this.handleAction('cancel', instance);
                }
            };
        }
    }

    /**
     * 处理操作
     */
    async handleAction(action, instance) {
        const { config } = instance;
        
        // 执行beforeClose回调
        if (config.beforeClose) {
            try {
                const shouldClose = await config.beforeClose(action, instance);
                if (!shouldClose) {
                    return;
                }
            } catch (error) {
                console.error('beforeClose callback error:', error);
                return;
            }
        }
        
        // 执行callback回调
        if (config.callback) {
            try {
                config.callback(action, instance);
            } catch (error) {
                console.error('callback error:', error);
            }
        }
        
        // 关闭对话框
        this.closeInstance(instance, action);
    }

    /**
     * 关闭实例
     */
    closeInstance(instance, action = 'cancel') {
        if (!instance.element) return;
        
        const overlay = instance.element.querySelector('.custom-confirm-overlay');
        
        // 添加关闭动画
        overlay.classList.add('closing');
        
        setTimeout(() => {
            // 从DOM中移除
            if (instance.element && instance.element.parentNode) {
                instance.element.parentNode.removeChild(instance.element);
            }
            
            // 从实例列表中移除
            const index = this.instances.indexOf(instance);
            if (index > -1) {
                this.instances.splice(index, 1);
            }
            
            // 处理Promise
            if (action === 'confirm') {
                instance.resolve({ action, instance });
            } else {
                instance.reject({ action, instance });
            }
        }, 300);
    }

    /**
     * 处理ESC键
     */
    handleEscapeKey() {
        const topInstance = this.instances[this.instances.length - 1];
        if (topInstance && topInstance.config.closeOnPressEscape) {
            this.handleAction('cancel', topInstance);
        }
    }

    /**
     * 关闭所有对话框
     */
    closeAll() {
        const instances = [...this.instances];
        instances.forEach(instance => {
            this.closeInstance(instance, 'cancel');
        });
    }

    /**
     * 信息提示
     */
    info(message, title = '提示') {
        return this.show({
            type: 'info',
            title,
            message,
            showCancelButton: false
        });
    }

    /**
     * 成功提示
     */
    success(message, title = '成功') {
        return this.show({
            type: 'success',
            title,
            message,
            showCancelButton: false
        });
    }

    /**
     * 警告提示
     */
    warning(message, title = '警告') {
        return this.show({
            type: 'warning',
            title,
            message,
            showCancelButton: false
        });
    }

    /**
     * 错误提示
     */
    error(message, title = '错误') {
        return this.show({
            type: 'error',
            title,
            message,
            showCancelButton: false
        });
    }

    /**
     * 确认对话框
     */
    confirm(message, title = '确认', options = {}) {
        return this.show(Object.assign({
            type: 'warning',
            title,
            message
        }, options));
    }
}

// 创建全局实例
const customConfirm = new CustomConfirm();

// 导出到全局
if (typeof window !== 'undefined') {
    window.customConfirm = customConfirm;
    window.CustomConfirm = CustomConfirm;
}

// 支持模块化
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { customConfirm, CustomConfirm };
}

if (typeof define === 'function' && define.amd) {
    define(function() {
        return { customConfirm, CustomConfirm };
    });
}